package cn.work.control;

import cn.work.bean.reservationBean;
import cn.work.bean.userbean;
import cn.work.service.ReservationService;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/*
   加载用户的预约数据
 */
@WebServlet(name = "loadReserServlet", value = "/loadReserServlet")
public class loadReserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        userbean user = (userbean) session.getAttribute("user");
        Integer userId = user.getUid();
        List<reservationBean> list = new ArrayList<>();
        ReservationService reservationService = new ReservationService();
        try {
            list = reservationService.getReservationListService(userId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        // 设置响应内容类型为 JSON
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

//         使用Gson将list转换为JSON
        Gson gson = new Gson();
        String jsonResponse = gson.toJson(list);  // 将列表转换为JSON字符串

        // 获取输出流并将JSON响应写入
        PrintWriter out = response.getWriter();
        out.write(jsonResponse);  // 返回JSON给客户端
        out.flush();
        out.close();
    }
}

